package me.sdau.spider.manager.modules.system.shiro;

import lombok.extern.slf4j.Slf4j;
import me.sdau.spider.manager.common.utils.MD5Util;
import me.sdau.spider.manager.modules.system.entity.User;
import me.sdau.spider.manager.modules.system.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Objects;
import java.util.Optional;

/**
 * @author zj
 * @date 2018/4/9 17:41
 */
@Slf4j
public class UserRealm extends AuthorizingRealm {
    private final int normal = 0;

    @Autowired
    private UserService userService;

    /**
     * 配置权限
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    /**
     * 校验账号
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        String password = new String((char[]) token.getCredentials());
        User user = Optional
                .ofNullable(userService.getUserByUsername(username))
                .orElseThrow(() -> new UnknownAccountException("用户不存在"));
        String encryptStr = MD5Util.encrypt(password, user.getSalt());


        // 密码错误
        if (!Objects.equals(encryptStr, user.getPassword())) {
            throw new IncorrectCredentialsException("账号或密码不正确");
        }
        // 账号状态不正常
        if (!Objects.equals(user.getStatus(), normal)) {
            throw new LockedAccountException("账号已被锁定,请联系管理员");
        }
//        return new SimpleAuthenticationInfo(
//                user,   // 用户名
//                user.getPassword(), // 密码
//                ByteSource.Util.bytes(user.getSalt()), // salt
//                getName()   // realm name
//        );
        return new SimpleAuthenticationInfo(user, password, getName());
    }
}
